/**
 *
 * @author pquiring
 *
 * Created : Nov 16, 2013
 */

import java.awt.*;
import java.awt.event.*;
import java.io.*;

import javaforce.*;

public class ProxyApp extends javax.swing.JFrame implements ActionListener, Logger {

  /**
   * Creates new form ProxyApp
   */
  public ProxyApp() {
    initComponents();
    setTitle("jf Web Proxy/" + Service.version);
    setPosition();
    //create tray icon to open app
    PopupMenu popup = new PopupMenu();
    show = new MenuItem("Show");
    show.addActionListener(this);
    popup.add(show);
    popup.addSeparator();
    exit = new MenuItem("Exit");
    exit.addActionListener(this);
    popup.add(exit);
    JFImage img = new JFImage();
    img.loadPNG(getClass().getClassLoader().getResourceAsStream("jfwebproxy.png"));
    setIconImage(img.getImage());
    icon = new TrayIcon(img.getImage(), "jf Web Proxy", popup);
    icon.addActionListener(this);
    tray = SystemTray.getSystemTray();
    try { tray.add(icon); } catch (Exception e) { JFLog.log(e); }
    readConfig();
    //start service
    service = new Service(8080, host.getText(), this, alwaysSecure.isSelected(), neverSecure.isSelected() , jsp.isSelected() ? "jsp" : "php");
    service.start();
  }

  public void readConfig() {
    try {
      BufferedReader br = new BufferedReader(new FileReader(JF.getUserPath() + "/.jfwebproxy.cfg"));
      String str = br.readLine();
      host.setText(str);
      String page = br.readLine();
      if (page.equals("php")) {
        php.setSelected(true);
      }
      String secure = br.readLine();
      if (secure.equals("always")) {
        alwaysSecure.setSelected(true);
      }
      else if (secure.equals("never")) {
        neverSecure.setSelected(true);
      }
    } catch (Exception e) {
      JFLog.log(e);
    }
  }

  public void writeConfig() {
    try {
      String cfg = host.getText() + "\n" + (jsp.isSelected() ? "jsp" : "php") + "\n";
      if (alwaysSecure.isSelected()) {
        cfg += "always\n";
      } else if (neverSecure.isSelected()) {
        cfg += "never\n";
      } else {
        cfg += "default\n";
      }
      FileOutputStream fos = new FileOutputStream(JF.getUserPath() + "/.jfwebproxy.cfg");
      fos.write(cfg.getBytes());
      fos.close();
    } catch (Exception e) {
      JFLog.log(e);
    }
  }

  public void restart() {
    service.close();
    JF.sleep(1000);
    service = new Service(8080, host.getText(), this, alwaysSecure.isSelected(), neverSecure.isSelected(), jsp.isSelected() ? "jsp" : "php");
    service.start();
  }

  public void actionPerformed(ActionEvent e) {
    Object o = e.getSource();
    if (o == exit) {
      System.exit(0);
    }
    if (o == show) {
      readConfig();
      setVisible(true);
    }
  }

  /**
   * This method is called from within the constructor to initialize the form.
   * WARNING: Do NOT modify this code. The content of this method is always
   * regenerated by the Form Editor.
   */
  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {

    buttonGroup1 = new javax.swing.ButtonGroup();
    buttonGroup2 = new javax.swing.ButtonGroup();
    save = new javax.swing.JButton();
    Cancel = new javax.swing.JButton();
    jLabel1 = new javax.swing.JLabel();
    host = new javax.swing.JTextField();
    jLabel2 = new javax.swing.JLabel();
    jsp = new javax.swing.JRadioButton();
    php = new javax.swing.JRadioButton();
    alwaysSecure = new javax.swing.JRadioButton();
    defaultSecure = new javax.swing.JRadioButton();
    neverSecure = new javax.swing.JRadioButton();

    setTitle("jf Web Proxy");

    save.setText("Save and Restart");
    save.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        saveActionPerformed(evt);
      }
    });

    Cancel.setText("Cancel");
    Cancel.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        CancelActionPerformed(evt);
      }
    });

    jLabel1.setText("Proxy Host:");

    host.setText("*.appspot.com");

    jLabel2.setText("Proxy Port : 8080");

    buttonGroup1.add(jsp);
    jsp.setSelected(true);
    jsp.setText("JSP");

    buttonGroup1.add(php);
    php.setText("PHP");

    buttonGroup2.add(alwaysSecure);
    alwaysSecure.setText("Always Secure");

    buttonGroup2.add(defaultSecure);
    defaultSecure.setSelected(true);
    defaultSecure.setText("Secure as requested");

    buttonGroup2.add(neverSecure);
    neverSecure.setText("Never Secure (not recommended)");

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addContainerGap()
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addGroup(layout.createSequentialGroup()
            .addGap(0, 0, Short.MAX_VALUE)
            .addComponent(Cancel)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(save))
          .addGroup(layout.createSequentialGroup()
            .addComponent(jLabel1)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(host))
          .addGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addComponent(jLabel2)
              .addGroup(layout.createSequentialGroup()
                .addComponent(jsp)
                .addGap(6, 6, 6)
                .addComponent(php))
              .addGroup(layout.createSequentialGroup()
                .addComponent(defaultSecure)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(alwaysSecure)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(neverSecure)))
            .addGap(0, 56, Short.MAX_VALUE)))
        .addContainerGap())
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addContainerGap()
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(jLabel1)
          .addComponent(host, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addGap(18, 18, 18)
        .addComponent(jLabel2)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(jsp)
          .addComponent(php))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(defaultSecure)
          .addComponent(alwaysSecure)
          .addComponent(neverSecure))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(save)
          .addComponent(Cancel))
        .addContainerGap())
    );

    pack();
  }// </editor-fold>//GEN-END:initComponents

  private void saveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveActionPerformed
    writeConfig();
    restart();
    setVisible(false);
  }//GEN-LAST:event_saveActionPerformed

  private void CancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CancelActionPerformed
    setVisible(false);
  }//GEN-LAST:event_CancelActionPerformed

  /**
   * @param args the command line arguments
   */
  public static void main(String args[]) {
    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
      public void run() {
        new ProxyApp();  //NOTE:Do NOT make it visible (it places icon in tray)
      }
    });
  }

  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JButton Cancel;
  private javax.swing.JRadioButton alwaysSecure;
  private javax.swing.ButtonGroup buttonGroup1;
  private javax.swing.ButtonGroup buttonGroup2;
  private javax.swing.JRadioButton defaultSecure;
  private javax.swing.JTextField host;
  private javax.swing.JLabel jLabel1;
  private javax.swing.JLabel jLabel2;
  private javax.swing.JRadioButton jsp;
  private javax.swing.JRadioButton neverSecure;
  private javax.swing.JRadioButton php;
  private javax.swing.JButton save;
  // End of variables declaration//GEN-END:variables

  public SystemTray tray;
  public TrayIcon icon;
  public MenuItem exit, show;
  public Service service;

  public void log(String msg) {}
  public void log(Throwable e) {}

  private void setPosition() {
    Dimension d = getSize();
    Rectangle s = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds();
    setLocation(s.width/2 - d.width/2, s.height/2 - d.height/2);
  }
}
